import { isConnected, deviceInfo, cpuUsageHistory, memoryUsageHistory, temperatureHistory, isDarkTheme } from '../app';
import firmwareVersionToString from '../global';
import { useEffect, useRef, useState } from 'preact/hooks';
import * as echarts from 'echarts';

export default function DeviceStatus() {
  const cpuChartRef = useRef(null);
  const memoryChartRef = useRef(null);
  const temperatureChartRef = useRef(null);
  const [charts, setCharts] = useState({
    cpu: null,
    memory: null,
    temperature: null
  });
  
  // 更新数据缓存的函数
  const updateDataCache = (currentValue, historySignal) => {
    const currentData = [...historySignal.value];
    if (currentData.length >= 301) {
      currentData.shift(); 
    }
    currentData.push(currentValue);
    historySignal.value = currentData;
    return currentData;
  };

  // 获取主题感知的图表配置
  const getChartOption = (data, title, unit = '%') => {
    const isDark = isDarkTheme.value;
    const textColor = isDark ? '#a6aec7' : '#64748b';
    const axisLineColor = isDark ? '#2b3142' : '#e2e8f0';
    const axisLabelColor = isDark ? '#7f889f' : '#94a3b8';
    const splitLineColor = isDark ? '#1e2433' : '#f1f5f9';
    const accentColor = isDark ? '#8ab4ff' : '#3b82f6';
    
    return {
      textStyle: {
        fontFamily: 'Arial, sans-serif',
        fontSize: 12,
        color: textColor
      },
      backgroundColor: 'transparent',
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '10%', 
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 301 }, (_, i) => i),
        axisLine: {
          lineStyle: {
            color: axisLineColor
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 50,
          color: axisLabelColor,
          formatter: (value) => `${value}s`
        },
        name: '', 
        nameLocation: 'middle',
        nameGap: 20
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: title === '温度' ? 100 : 100,
        axisLabel: {
          color: axisLabelColor,
          formatter: `{value}${unit}`
        },
        axisLine: {
          lineStyle: {
            color: axisLineColor
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: splitLineColor
          }
        }
      },
      legend: {
        show: false,
        data: ['使用率'],
        top: '5%'
      },
      series: [{
        name: '使用率',
        data: data,
        type: 'line',
        smooth: true,
        showSymbol: false,
        symbol: 'none',
        lineStyle: {
          color: accentColor,
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: isDark ? 'rgba(138, 180, 255, 0.25)' : 'rgba(59, 130, 246, 0.25)'
            }, {
              offset: 1, color: isDark ? 'rgba(138, 180, 255, 0)' : 'rgba(59, 130, 246, 0)'
            }]
          }
        },
        itemStyle: {
          color: accentColor
        }
      }]
    };
  };

  // 初始化图表
  useEffect(() => {
    if (!cpuChartRef.current || !memoryChartRef.current || !temperatureChartRef.current) return;

    const cpuChart = echarts.init(cpuChartRef.current);
    const memoryChart = echarts.init(memoryChartRef.current);
    const temperatureChart = echarts.init(temperatureChartRef.current);
    
    setCharts({
      cpu: cpuChart,
      memory: memoryChart,
      temperature: temperatureChart
    });

    const cpuOption = getChartOption(cpuUsageHistory.value, 'CPU使用率', '%');
    const memoryOption = getChartOption(memoryUsageHistory.value, '内存使用率', '%');
    const temperatureOption = getChartOption(temperatureHistory.value, '温度', '°C');

    cpuChart.setOption(cpuOption);
    memoryChart.setOption(memoryOption);
    temperatureChart.setOption(temperatureOption);

    const handleResize = () => {
      cpuChart.resize();
      memoryChart.resize();
      temperatureChart.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      cpuChart.dispose();
      memoryChart.dispose();
      temperatureChart.dispose();
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 主题切换时重新渲染图表
  useEffect(() => {
    if (!charts.cpu || !charts.memory || !charts.temperature) return;
    
    const cpuOption = getChartOption(cpuUsageHistory.value, 'CPU使用率', '%');
    const memoryOption = getChartOption(memoryUsageHistory.value, '内存使用率', '%');
    const temperatureOption = getChartOption(temperatureHistory.value, '温度', '°C');
    
    charts.cpu.setOption(cpuOption);
    charts.memory.setOption(memoryOption);
    charts.temperature.setOption(temperatureOption);
  }, [isDarkTheme.value, charts]);

  // 监听设备数据变化并更新图表
  useEffect(() => {
    if (!isConnected.value || !charts.cpu || !charts.memory || !charts.temperature) return;

    const deviceData = deviceInfo.value;
    if (!deviceData || typeof deviceData !== 'object') return;

    const newCpuUsage = deviceData['cpuUsage'] || 0;
    const newMemoryUsage = deviceData['memoryUsage'] || 0;
    const newTemperature = deviceData['temperature'] || 0;
    
    const newCpuData = updateDataCache(newCpuUsage, cpuUsageHistory);
    const newMemoryData = updateDataCache(newMemoryUsage, memoryUsageHistory);
    const newTemperatureData = updateDataCache(newTemperature, temperatureHistory);
    
    // 更新图表数据
    if (charts.cpu) {
      charts.cpu.setOption({
        series: [{
          data: newCpuData
        }]
      });
    }
    
    if (charts.memory) {
      charts.memory.setOption({
        series: [{
          data: newMemoryData
        }]
      });
    }

    if (charts.temperature) {
      charts.temperature.setOption({
        series: [{
          data: newTemperatureData
        }]
      });
    }
  }, [deviceInfo.value, isConnected.value, charts]);

  // 设备信息部分
  const deviceData = typeof deviceInfo.value === 'string' ? JSON.parse(deviceInfo.value) : deviceInfo.value;
  
  // 处理设备重启
  const handleReboot = async () => {
    if (!window.confirm('确认重启设备？')) {
      return;
    }
    
    // 发送重启请求但不等待返回
    fetch('/api/reboot', {
      method: 'POST'
    }).catch(err => {
    });
    
    // 立即提示用户
    alert('重启请求已发送，设备重启中 ...');
    isConnected.value = false;
  };

  return (
    <div class="h-full p-6">
      <div class="flex justify-between items-center mb-4">
        <h1 class="text-xl font-medium flex items-center adonis-section-title">
          <div class="w-1 h-5 mr-3" style={{ background: 'var(--adonis-accent)' }}></div>
          设备状态
        </h1>
        <button
          onClick={handleReboot}
          disabled={!isConnected.value}
          class="group relative inline-flex items-center px-4 py-2 rounded-lg font-medium text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2"
          style={{
            background: isConnected.value ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)' : 'var(--adonis-panel-2)',
            color: isConnected.value ? 'white' : 'var(--adonis-text-muted)',
            border: '1px solid',
            borderColor: isConnected.value ? '#dc2626' : 'var(--adonis-border)',
            cursor: isConnected.value ? 'pointer' : 'not-allowed',
            opacity: isConnected.value ? 1 : 0.6,
            boxShadow: isConnected.value ? '0 4px 12px rgba(239, 68, 68, 0.3)' : 'none'
          }}
          title={isConnected.value ? '重启设备' : '设备未连接'}
        >
          <div class="flex items-center space-x-2">
            <svg 
              class={`w-4 h-4 transition-transform duration-200 ${isConnected.value ? 'group-hover:rotate-180' : ''}`} 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            <span>重启设备</span>
          </div>
          {isConnected.value && (
            <div class="absolute inset-0 rounded-lg bg-white opacity-0 group-hover:opacity-10 transition-opacity duration-200"></div>
          )}
        </button>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <div class="adonis-card p-6">
          <h2 class="text-lg font-semibold adonis-section-title mb-4">系统信息</h2>
          <ul class="space-y-3">
            <li class="flex justify-between items-center pb-2" style={{ borderBottom: '1px solid var(--adonis-border)' }}>
              <span style={{ color: 'var(--adonis-text-muted)' }}>设备名称:</span>
              <span class="font-medium">{deviceData?.name || '未知'}</span>
            </li>
            <li class="flex justify-between items-center pb-2" style={{ borderBottom: '1px solid var(--adonis-border)' }}>
              <span style={{ color: 'var(--adonis-text-muted)' }}>固件版本:</span>
              <span class="font-medium">{firmwareVersionToString(deviceData?.firmwareVersion) || '未知'}</span>
            </li>
            <li class="flex justify-between items-center pb-2" style={{ borderBottom: '1px solid var(--adonis-border)' }}>
              <span style={{ color: 'var(--adonis-text-muted)' }}>芯片序列号:</span>
              <span class="font-medium">
                {deviceData?.chipId ? deviceData.chipId : '未知'}
              </span>
            </li>
            <li class="flex justify-between items-center">
              <span style={{ color: 'var(--adonis-text-muted)' }}>运行时间:</span>
              <span class="font-medium">
                {deviceData?.uptime 
                  ? `${String(Math.floor(deviceData.uptime / 3600)).padStart(2, '0')}:${String(Math.floor((deviceData.uptime % 3600) / 60)).padStart(2, '0')}:${String(Math.floor(deviceData.uptime % 60)).padStart(2, '0')}` 
                  : '未知'
                }
              </span>
            </li>
          </ul>
        </div>
        
        
        <div class="adonis-card p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold adonis-section-title">CPU使用率</h2>
            <div class="text-right">
              <div class="text-2xl font-bold" style={{ color: 'var(--adonis-accent)' }}>
                {cpuUsageHistory.value[cpuUsageHistory.value.length - 1]?.toFixed(1) || '0.0'}%
              </div>
            </div>
          </div>
          <div ref={cpuChartRef} style={{ height: '300px' }}></div>
        </div>
        
        <div class="adonis-card p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold adonis-section-title">内存使用率</h2>
            <div class="text-right">
              <div class="text-2xl font-bold" style={{ color: 'var(--adonis-success)' }}>
                {memoryUsageHistory.value[memoryUsageHistory.value.length - 1]?.toFixed(1) || '0.0'}%
              </div>
            </div>
          </div>
          <div ref={memoryChartRef} style={{ height: '300px' }}></div>
        </div>

        <div class="adonis-card p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold adonis-section-title">片内温度</h2>
            <div class="text-right">
              <div class="text-2xl font-bold" style={{ color: 'var(--adonis-danger)' }}>
                {temperatureHistory.value[temperatureHistory.value.length - 1]?.toFixed(1) || '0.0'}°C
              </div>
            </div>
          </div>
          <div ref={temperatureChartRef} style={{ height: '300px' }}></div>
        </div>
      </div>
    </div>
  );
}